package com.orange.base.core.util;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;

import org.springframework.stereotype.Component;

/**
 * spring工具类
 * 
 * @author wlwang
 *
 */
@Component
@Lazy(false)
public final class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext ac = null;

    public static ApplicationContext getApplicationContext() throws Exception {
        return SpringUtil.ac;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        SpringUtil.ac = ac;
    }

    /**
     * 获取上下文中配置的Bean对象
     */
    public static <T> T getBean(Class<T> clazz) throws Exception {
        return ac.getBean(clazz);
    }

    public static <T> T getBeanByName(Class<T> clazz, String name) throws Exception {
        return ac.getBean(name, clazz);
    }

    /**
     * 根据名称获取对象
     */
    public static Object getBean(String name) throws Exception {
        return ac.getBean(name);
    }

    /**
     * 根据类型返回bean
     * 
     * @param clazz
     * @return
     * @throws Exception
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) throws Exception {
        return ac.getBeansOfType(clazz);
    }

}
